package com.blast.manager.delay.presenter

import android.text.TextUtils
import com.blast.manager.delay.DelayActivity
import com.blast.manager.delay.ui.UnauthorizedActivity
import com.wxl.common.AppContext
import com.wxl.common.base.AbsActivity
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.room.entity.UnApplyBlastEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.DateUtils
import com.wxl.common.util.ObservableUtil
import com.wxl.common.wiget.NotAuthTipPop
import com.wxl.common.wiget.ProgressUpdatePop
import io.reactivex.ObservableOnSubscribe
import io.reactivex.functions.Action


/**
 * 授权检查
 */
class CheckAuthPresenter : AbsDelayPresenter() {

    private var mProgressUpdatePop:ProgressUpdatePop?=null
    private var isCanKeyEvent = true

    override fun onDelayCreated(vararg args: Any) {

    }


    /**
     * 开始授权检查
     */
    fun startAuthCheck() {
        if(mProgressUpdatePop != null && mProgressUpdatePop!!.isShow )return
        if(getPresenter(ShowDelayDataPresenter::class.java).getData().isEmpty() ||  AppContext.appContext.isCheckModel()){
            (context as AbsActivity).finish()
            return
        }
        mProgressUpdatePop = ProgressUpdatePop.show(context)
        ProgressUpdatePop.updateProgress(0, "正在进行授权检查...", "授权检查", 100)
        (context as DelayActivity).addLog("授权检查","${getPresenter(ShowDelayDataPresenter::class.java).getTotal()}条")
        ObservableUtil.doNext(ObservableOnSubscribe { oe ->
            getPresenter(ShowDelayDataPresenter::class.java).getData().forEach {
                if (TextUtils.isEmpty(it.password)) {
                    oe.onNext(true)
                    return@ObservableOnSubscribe
                }
            }
            oe.onNext(false)
        }, object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                if (t) {
                    checkDbAuthFile()
                } else {
                    (context as DelayActivity).addLog("授权检查","已全部授权")
                    ProgressUpdatePop.updateProgress(100, "已完成授权检查...", "授权检查", 100)
                    delayFinish()
                }
            }
        })

    }

    private fun delayFinish(){
        ObservableUtil.delay(2000, Runnable {
            (context as AbsActivity).finish()
        })
    }

    /**
     * 检查本地是否有对应的授权文件
     */
    private fun checkDbAuthFile() {
        (context as DelayActivity).addLog("授权检查","检查离线授权文件")
        ProgressUpdatePop.updateProgress(20, "正在进行授权检查...", "授权检查", 100)
        DBHelper.queryAppledBlastData(object :
            ObservableUtil.Companion.OnNextCallback<List<UnApplyBlastEntity>>() {
            override fun onNext(t: List<UnApplyBlastEntity>) {
                if (t.isNotEmpty()) {
                    checkDbAuthFileDue(t)
                } else {
                    checkAuthCase()
                }
            }
        })
    }

    /**
     * 检查授权文件是否过期
     */
    private fun checkDbAuthFileDue(t: List<UnApplyBlastEntity>) {
        (context as DelayActivity).addLog("授权检查","找到离线授权文件${t.size}个")
        ProgressUpdatePop.updateProgress(40, "正在进行授权检查...", "授权检查", 100)
        ObservableUtil.doNext(ObservableOnSubscribe {
            val regular = arrayListOf<UnApplyBlastEntity>()
            t.forEach {
                it.takeIf {
                    it.lgs != null && it.lgs.lg != null && it.lgs.lg.isNotEmpty() && !TextUtils.isEmpty(
                        it.lgs.lg[0].yxq
                    )
                }?.apply {
                    if(DateUtils.getTime(this.lgs.lg[0].yxq) > System.currentTimeMillis()) {
                        regular.add(this)
                    } else {
                        DBHelper.deleteUnApplyBlastData(object : ObservableUtil.Companion.OnNextCallback<Boolean>(){
                            override fun onNext(t: Boolean) {
                            }
                        },this)
                    }
                }
            }
            it.onNext(regular)
        }, object : ObservableUtil.Companion.OnNextCallback<List<UnApplyBlastEntity>>() {
            override fun onNext(t: List<UnApplyBlastEntity>) {
                if (t.isNotEmpty()) {
                    auth(t)
                } else {
                    checkAuthCase()
                }
            }
        })
    }

    /**
     * 授权
     */
    private fun auth(data: List<UnApplyBlastEntity>) {
        (context as DelayActivity).addLog("授权检查","正在进行授权")
        ProgressUpdatePop.updateProgress(60, "正在进行授权...", "授权检查", 100)
        ObservableUtil.doNext(ObservableOnSubscribe {
            var update = false
            data.forEach { abe ->
                getPresenter(ShowDelayDataPresenter::class.java).getData().forEach {
                    if (TextUtils.equals(abe.lgs.lg[0].uid, it.UID)) {
                        it.password = abe.lgs.lg[0].gzm
                        update = true
                    }
                }
            }
            it.onNext(update)
        }, object : ObservableUtil.Companion.OnNextCallback<Boolean>() {
            override fun onNext(t: Boolean) {
                (context as DelayActivity).addLog("授权检查","授权完成")
                if (t) {
                    AppContext.appContext.saveAuthDmInfo(data[0].licenseFileModel)
                    DBHelper.updateLeiGuan(object :
                        ObservableUtil.Companion.OnNextCallback<Boolean>() {
                        override fun onNext(t: Boolean) {
                            checkAuthCase()
                        }
                    }, *getPresenter(ShowDelayDataPresenter::class.java).getData().toTypedArray())
                } else {
                    checkAuthCase()
                }
            }
        })

    }


    /**
     * 检查授权完成后的情况
     */
    private fun checkAuthCase() {
        var mTermNum = 0
        (context as DelayActivity).addLog("授权检查","检查授权结果")
        ProgressUpdatePop.updateProgress(80, "正在进行授权检查...", "授权检查", 100)
        ObservableUtil.doNext(ObservableOnSubscribe {
            val mNoAuthorizeList = arrayListOf<LeiGuanEntity>()
            getPresenter(ShowDelayDataPresenter::class.java).getData().forEach {
                if (TextUtils.isEmpty(it.password)) {
                    mNoAuthorizeList.add(it)
                }
                if (it.term != 0.0) {
                    mTermNum++
                }
            }
            it.onNext(mNoAuthorizeList)
        }, object : ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
            override fun onNext(t: List<LeiGuanEntity>) {
                if (t.isEmpty()) {
                    ProgressUpdatePop.updateProgress(100, "已完成授权...", "授权检查", 100)
                    delayFinish()
                } else {
                    ProgressUpdatePop.updateProgress(100, "已完成授权检查...", "授权检查", 100)
                    showNoAuthorizeWindow(mTermNum, t)
                }
            }
        })
    }


    /**
     * 显示未授权提示框
     */
    private fun showNoAuthorizeWindow(mTermNum: Int, mNoAuthorizeList: List<LeiGuanEntity>) {
        (context as DelayActivity).addLog("授权检查","有${mNoAuthorizeList.size}未授权")
        ObservableUtil.delay(2000, Runnable {
            NotAuthTipPop.show(context,
                mNoAuthorizeList.size.toString(),
                mTermNum.toString(),
                Action {
                    (context as DelayActivity).addLog("授权检查","返回")
                    (context as AbsActivity).finish()
                },
                Action {
                    (context as DelayActivity).addLog("授权检查","确定->去未授权列表")
                    UnauthorizedActivity.start(context,mNoAuthorizeList as ArrayList)
                })
        })
    }

}